package com.javasea.qrprint.controller;

import com.javasea.qrprint.util.FxImageUtil;
import com.javasea.qrprint.util.TrayOperatorUtil;
import com.javasea.qrprint.util.TscCommandUtil;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;

import java.io.IOException;

public class RootController {

    @FXML
    private Pane rootPane;

    @FXML
    private TextField printTextInfo;

    @FXML
    private TextField printQrInfo;

    @FXML
    private VBox fxmlPanes;

    @FXML
    private ChoiceBox<SampleController> childControllersChoiceBox;

    @FXML
    private ImageView snapshotImageView;

    @FXML
    private ImageView bitmapImageView;

    @FXML
    private void setPrintTextInfo() {
        String text = this.printTextInfo.getText();
        this.childControllersChoiceBox.getValue().setText(text);
    }

    @FXML
    private void setPrintQrInfo(){
        String qr = this.printQrInfo.getText();
        this.childControllersChoiceBox.getValue().setQr(qr);
    }

    public void setSnapShot(WritableImage writableImage) {
        this.snapshotImageView.setImage(writableImage);
    }

    public void takeSnapShot() {
        WritableImage image = FxImageUtil.takeSnapShot(this.childControllersChoiceBox.getValue().getPane());
        this.setSnapShot(image);
    }

    public void addChildPane(SampleController controller) {
        this.childControllersChoiceBox.getItems().add(controller);
        this.fxmlPanes.getChildren().add(controller.getPane());
    }

    public void setChildPaneController(){
        SampleController sampleController = this.getControllerByClass(SampleController.class);
        this.childControllersChoiceBox.setValue(sampleController);
    }

    @FXML
    public void printCmdToPrinter() throws IOException {
        this.takeSnapShot();
        this.childControllersChoiceBox.getValue().refinePane();
        byte[] bytes = TscCommandUtil.makeBitmapAndCmd(this.snapshotImageView.getImage(), bitmapImageView);
        // TODO print
//        TscCommandUtil.executePrintCmd(bytes);
        TrayOperatorUtil.trayMessage("开始打印 公司简介二维码");
    }

    @FXML
    public void setParam(){
        setPrintTextInfo();
        setPrintQrInfo();
    }

    public <T> T getControllerByClass(Class<T> clazz) {
        for (Object controller : this.childControllersChoiceBox.getItems()) {
            if (clazz.isInstance(controller)) {
                return (T) controller;
            }
        }
        throw new RuntimeException("没有这个类型的controller对象");
    }

}
